//
//  SNKMeViewController.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/8.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "SNKMeViewController.h"

#import "SNKSettingHeaderView.h"
#import "SNKSettingCell.h"
#import "XFLoginViewController.h"
#import "SNKUserDetailController.h"

#import "SNKSettingItem.h"
#import "SNKSettingArrowItem.h"
#import "SNKSettingSwitchItem.h"
#import "SNKSettingGroup.h"

#import "SNKCollectViewController.h"
#import "SNKChatViewController.h"
#import "SNKAboutUsController.h"

#import "SDImageCache.h"
//#import "EMSDK.h"
#import "SNKShareManager.h"
#import "MBProgressHUD+Extion.h"

#import <DKNightVersion/DKNightVersion.h>

#import <AVOSCloud.h>

@interface SNKMeViewController ()<UITableViewDataSource, UITableViewDelegate>

/** 头部视图 */
@property (nonatomic, weak) SNKSettingHeaderView *headerView;
/** 表格视图 */
@property (nonatomic, weak) UITableView *tableView;
/** 存放组模型的数组 */
@property (nonatomic , strong) NSMutableArray<SNKSettingGroup *> *groupsArray;
/** 当前缓存 */
@property (nonatomic , strong) NSString *clearCacheName;

@property (nonatomic , copy) NSString * chatCount;     //未读消息数目
@property (nonatomic , strong) NSArray *conversations;

@end

@implementation SNKMeViewController

#pragma mark - 懒加载
- (NSMutableArray<SNKSettingGroup *> *)groupsArray{
    if (!_groupsArray) {
        _groupsArray = [NSMutableArray array];
    }
    return _groupsArray;
}

- (NSArray *)conversations {
    if (!_conversations) {
        _conversations = [NSArray array];
    }
    return _conversations;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    IMP_BLOCK_SELF(SNKMeViewController);
    
    // 监听未读消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChatCountChanged:) name:@"ChatCount" object:nil];
    // 添加环信代理
//    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    // 添加Header
    SNKSettingHeaderView *headerView = [[SNKSettingHeaderView alloc] init];
    headerView.loginBlock = ^{  // 登录的Block
        XFLoginViewController *loginVc = [[XFLoginViewController alloc] init];
        [block_self presentViewController:loginVc animated:YES completion:nil];
    };
    headerView.userDetailBlock = ^{
        SNKUserDetailController *userDetailVc = [[SNKUserDetailController alloc] init];
        [block_self.navigationController pushViewController:userDetailVc animated:YES];
    };
    self.headerView = headerView;
    
    // 添加tableView   *************  -20是状态栏的高度
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -20, SCREENW, SCREENH) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    tableView.tableHeaderView = headerView;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView = tableView;
    
    
    // 获取会话记录
    [self loadConversations];
    
    // 设置第0组数据
    [self setupGroup0];
    // 设置第1组数据
    [self setupGroup1];
    
    // 颜色相关
    [self changeColor];
}

- (void)changeColor {
    self.tableView.dk_backgroundColorPicker = DKColorPickerWithKey(SEP);
}

-(void)loadConversations{
    //获取历史会话记录
//    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
//    if (conversations.count == 0) {
//        conversations =  [[EMClient sharedClient].chatManager loadAllConversationsFromDB];
//    }
//    self.conversations = conversations;
    //显示总的未读数
    [self showTabBarBadge];
}

- (void)showTabBarBadge{
    NSInteger totalUnreadCount = 0;
//    for (EMConversation *conversation in self.conversations) {
//        totalUnreadCount += [conversation unreadMessagesCount];
//    }
    KLog(@"未读消息总数:%ld",(long)totalUnreadCount);
    self.chatCount = [NSString stringWithFormat:@"%ld",(long)totalUnreadCount];
}

#pragma mark - 接收到聊天消息数改变
- (void)ChatCountChanged:(NSNotification *)noti
{
    self.chatCount = noti.object;
    self.groupsArray = nil;
    [self setupGroup0];
    [self setupGroup1];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 恢复代理
    self.tableView.delegate = self;
    [self.navigationController setNavigationBarHidden:YES];
    
    float tmpSize = [[SDImageCache sharedImageCache] getSize];
    NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"%.1fMB", tmpSize/(1024*1024)] : [NSString stringWithFormat:@"%.1fKB",tmpSize * 1024];
    self.clearCacheName = clearCacheName;
    
    self.groupsArray = nil;
    [self setupGroup0];
    [self setupGroup1];
    [self.tableView reloadData];
    
    // 更新头像
    [self.headerView updateProfile];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 清空tableView的代理
    self.tableView.delegate = nil;
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)setupGroup0
{
    BOOL isLogin = nil;
    if ([AVUser currentUser].objectId != nil) { // 登录了
        isLogin = YES;
    }else {
        isLogin = NO;
    }
    
    // 收藏
    SNKSettingItem *collect = [SNKSettingArrowItem itemWithItem:@"userCenterCollect" title:@"收藏" VcClass:(isLogin?[SNKCollectViewController class]:[XFLoginViewController class])];
    
    // 夜间模式
    SNKSettingItem *nightMode = [SNKSettingSwitchItem itemWithItem:@"userCenter_NightMode" title:@"夜间模式"];
    
    // Group0
    SNKSettingGroup *group0 = [[SNKSettingGroup alloc] init];
    group0.items = @[collect,nightMode];
    [self.groupsArray addObject:group0];
}

- (void)setupGroup1
{
    IMP_BLOCK_SELF(SNKMeViewController);
    
    // 帮助与反馈
    SNKSettingItem *helpAndFeedback = [SNKSettingArrowItem itemWithItem:@"userCenter_FeedBack" title:@"帮助与反馈" subtitle:self.chatCount VcClass:[SNKChatViewController class]];
    
    // 分享给好友
    SNKSettingItem *shareToFriends = [SNKSettingArrowItem itemWithItem:@"beauty_share" title:@"分享给好友" VcClass:nil];
    shareToFriends.optionHandle = ^{
        [[SNKShareManager sharedInstance] shareWeiboWithTitle:nil text:nil images:nil url:nil dismissBlock:^{
            [block_self.navigationController popViewControllerAnimated:YES];
        }];
    };
    
    // 清除缓存
    SNKSettingItem *clearCache = [SNKSettingArrowItem itemWithItem:@"setting_clearCache" title:@"清除缓存" subTitle:self.clearCacheName];
    clearCache.optionHandle = ^{
        [block_self click];
    };
    
    // 关于
    SNKSettingItem *aboutMe = [SNKSettingArrowItem itemWithItem:@"aboutMe" title:@"关于我们" VcClass:nil];
    aboutMe.optionHandle = ^{
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"关于我们" message:@"当前版本: 1.0.0" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
        SNKAboutUsController *aboutUsVc = [[SNKAboutUsController alloc] init];
        [block_self.navigationController pushViewController:aboutUsVc animated:YES];
    };
    
    //group1
    SNKSettingGroup *group1 = [[SNKSettingGroup alloc] init];
    group1.items = @[helpAndFeedback,shareToFriends,clearCache,aboutMe];
    [self.groupsArray addObject:group1];
}

#pragma mark - 清除缓存
- (void)click
{
    IMP_BLOCK_SELF(SNKMeViewController);
    MBProgressHUD *hud = [[MBProgressHUD alloc] init];
    [[[UIApplication sharedApplication].windows firstObject] addSubview:hud];
    //加载条上显示文本
    hud.labelText = @"急速清理中";
    //置当前的view为灰度
    hud.dimBackground = YES;
    //设置对话框样式
    hud.mode = MBProgressHUDModeDeterminate;
    [hud showAnimated:YES whileExecutingBlock:^{
        while (hud.progress < 1.0) {
            hud.progress += 0.01;
            [NSThread sleepForTimeInterval:0.02];
        }
        hud.labelText = @"清理完成";
    } completionBlock:^{
        [[SDImageCache sharedImageCache] clearDisk];
        [[SDImageCache sharedImageCache] clearMemory];
        block_self.clearCacheName = @"0.0KB";
        block_self.groupsArray = nil;
        [block_self setupGroup0];
        [block_self setupGroup1];
        [block_self.tableView reloadData];
        [hud removeFromSuperview];
    }];
}

#pragma mark - tableView数据源代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.groupsArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    SNKSettingGroup *group = self.groupsArray[section];
    return group.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SNKSettingCell *cell = [SNKSettingCell cellWithTableView:tableView];
    
    cell.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
    cell.textLabel.dk_textColorPicker = DKColorPickerWithKey(TEXT);
    
    SNKSettingGroup *group = self.groupsArray[indexPath.section];
    cell.item = group.items[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 取出item
    SNKSettingGroup *group = self.groupsArray[indexPath.section];
    SNKSettingItem *item = group.items[indexPath.row];
    
    // 如果带Block,就执行
    if (item.optionHandle) {
        item.optionHandle();
    }else if ([item isKindOfClass:[SNKSettingArrowItem class]]) {  // 带箭头
        SNKSettingArrowItem *arrowItem = (SNKSettingArrowItem *)item;
        if (arrowItem.VcClass == nil) return;
        
        if (arrowItem.VcClass == [SNKChatViewController class]) {  // 聊天view
            SNKChatViewController *chatVc = [[SNKChatViewController alloc] init];
            chatVc.title = arrowItem.title;
            [self.navigationController pushViewController:chatVc animated:YES];
            
        }else if (arrowItem.VcClass == [XFLoginViewController class]) {
            XFLoginViewController *loginVc = [[XFLoginViewController alloc] init];
            [self presentViewController:loginVc animated:YES completion:nil];
            
        }else{  // 跳转普通的UIViewController,在这里涵盖了CollectView
            UIViewController *vc = [[arrowItem.VcClass alloc] init];
            vc.view.backgroundColor = [UIColor whiteColor];
            vc.title = arrowItem.title;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }

}

// 自定义footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

@end
